package com.example.springboot.config.upload;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @desc 文件上次及下载操作
 * @Author wangsh
 * @date 2018/5/6 16:10
 * @return
 */
@RestController
@RequestMapping("/file")
public class FileController {

	private String path = "d:\\";

	/**
	 * @return
	 * @desc 文件上次到本地
	 * @Author wangsh
	 * @date 2018/5/6 16:10
	 */
	@PostMapping("/upload")
	public FileInfo upload(MultipartFile file) throws Exception {

		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());
		System.out.println(file.getSize());

		File localFile = new File(path, file.getOriginalFilename());

		file.transferTo(localFile);

		return new FileInfo(localFile.getAbsolutePath());
	}

	/**
	 * 文件下载
	 *
	 * @param fileName
	 * @param request
	 * @param response
	 */
	@GetMapping("/{fileName}")
	public void download(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
		try (InputStream inputStream = new FileInputStream(new File(path, fileName));
			 OutputStream outputStream = response.getOutputStream();) {

			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

			IOUtils.copy(inputStream, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}